#!/usr/bin/env groovy

@Library('pipeline-library') _

pipeline {
    agent {
        label 'ec2-jdk17'
    }

    triggers {
        pollSCM('H 23 * * *')
    }

    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
        timeout(time: 30)
    }

    environment {
        MAVEN_OPTS = '-Xms1024m -Xmx4096m -Dmaven.wagon.http.retryHandler.class=standard -Dmaven.wagon.http.retryHandler.count=3 -Dmaven.wagon.httpconnectionManager.ttlSeconds=125'
    }

    stages {
        stage ('Build') {
            steps {
                echo 'Building DHIS2 ...'
                script {
                    withMaven(options: [artifactsPublisher(disabled: true)]) {
                        sh 'mvn -X -T 4 --batch-mode --no-transfer-progress clean install -f dhis-2/pom.xml -P -default --update-snapshots -pl -dhis-test-coverage'
                    }
                }
            }
        }

        stage ('Sync WAR') {
            steps {
                echo 'Syncing WAR ...'
                sh 'curl "https://raw.githubusercontent.com/dhis2/dhis2-server-setup/master/ci/scripts/copy-war-s3.sh" -O'
                sh 'chmod +x copy-war-s3.sh'
                sh './copy-war-s3.sh eos ${GIT_BRANCH}'
            }
        }
    }

    post {
        failure {
            script {
                slack.sendMessage(
                    '#ff0000',
                    slack.buildUrl() + "\nLatest run on ${GIT_BRANCH} failed and needs investigation. :detective-duck:\nCommit: <${GIT_URL}/commit/${GIT_COMMIT}|${GIT_COMMIT}>",
                    'team-backend'
                )
            }
        }

        aborted {
            script {
                slack.sendTimedoutMessage()
            }
        }
    }
}
